<template>
  <div class="withdrawal-container">
    <h1>退课</h1>

    <table v-if="paginatedCourses.length > 0">
      <thead>
      <tr>
        <th>课程编号</th>
        <th>课程名称</th>
        <th>上课时间</th>
        <th>上课地点</th>
        <th>教师姓名</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(course, index) in paginatedCourses" :key="index">
        <td>{{ course.cno }}</td>
        <td>{{ course.cname }}</td>
        <td>{{ course.time }}</td>
        <td>{{ course.address }}</td>
        <td>{{ course.tname }}</td>
        <td>
          <button
              :disabled="!canWithdraw(course)"
              @click="withdrawCourse(course)"
          >
            {{ canWithdraw(course) ? '退课' : '时间已过' }}
          </button>
        </td>
      </tr>
      </tbody>
    </table>
    <p v-else>您当前没有选任何课程。</p>

    <!-- 分页控件 -->
    <div class="pagination" v-if="filteredCourses.length > 0">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { computed, onMounted, ref } from 'vue';
import { useRoute } from "vue-router";

const route = useRoute();
const id = route.query.id;
onMounted(() => {
  getData();
});

// 原始课程数据
const courses = ref([]);

// 搜索查询字符串（如果需要的话）
const searchQuery = ref('');

// 根据原始数据和搜索查询计算过滤后的课程列表
const filteredCourses = computed(() => {
  if (!searchQuery.value) return courses.value;

  const queryLower = searchQuery.value.toLowerCase();
  return courses.value.filter(course =>
      course.cname.toLowerCase().includes(queryLower) ||
      course.tname.toLowerCase().includes(queryLower)
  );
});

// 获取数据并存储到courses中
const getData = async () => {
  try {
    const response = await axios.get('http://localhost:8080/getMycourse', {
      params: {
        sno: id
      }
    });
    courses.value = response.data;
    // 初始化分页参数
    totalPages.value = Math.ceil(filteredCourses.value.length / itemsPerPage.value);
  } catch (error) {
    console.error(error);
  }
};

// 分页相关变量
const currentPage = ref(1);
const itemsPerPage = ref(5);
const totalPages = ref(1);

// 计算分页后的课程列表
const paginatedCourses = computed(() => {
  const startIndex = (currentPage.value - 1) * itemsPerPage.value;
  const endIndex = startIndex + itemsPerPage.value;
  return filteredCourses.value.slice(startIndex, endIndex);
});

// 检查是否可以退课
function canWithdraw(course) {
  // 这里可以根据实际情况添加更多的检查条件
  return course.isopen === 1;
}

// 退课操作
function withdrawCourse(course) {
  axios.delete(`http://localhost:8080/delMycourse?cno=${course.cno}&sno=${id}`)
      .then(() => {
        // 成功后重新获取数据以更新UI
        getData();
        window.alert('退课成功');
      })
      .catch(error => {
        window.alert('退课失败');
      });
}

// 分页控制方法
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};
</script>

<style scoped>
.withdrawal-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
}

table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
}

th, td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

tr:hover {
  background-color: #f1f1f1;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.pagination button {
  margin: 0 5px;
}

button {
  background-color: #4fd96b;
  color: white;
  border: none;
  cursor: pointer;
  padding: 5px 10px;
}

button:hover {
  background-color: #c9302c;
}

button:disabled {
  background-color: gray;
  cursor: not-allowed;
}
</style>